package com.yiyukongjian.house;

import java.io.Serializable;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yiyukongjian.house.dataaccess.HouseInforDataAccessor;
import com.yiyukongjian.house.dataaccess.HouseInforDataAccessorFactory;
import com.yiyukongjian.house.widget.ProcessingBar;
import com.yiyukongjian.house.widget.TopNavigator;

public class QueryConditionActivity extends Activity {

    //static final int DATE_DIALOG_ID = 1;   
    private TextView mDateDisplay;
    
    // date and time
    private int mYear;
    private int mMonth;
    private int mDay;
    
    private EditText mFWDZet = null;
    private EditText mFZXMet = null;
    private EditText mFZZJHMZet = null;
    private EditText mCZRXMet = null;
    private EditText mCZRZJHMet = null; 
    
    private ProcessingBar mPb = null;
    private View mQueryForm = null;
    
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		//设置无标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_query);
	
		mDateDisplay = (TextView) findViewById(R.id.query_show_date);
		
		Button pickDate = (Button) findViewById(R.id.query_pick_date);
        pickDate.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("deprecation")
			public void onClick(View v) {
                showDialog(0);
            }
        });
        
        TopNavigator nav = (TopNavigator) findViewById(R.id.topnavigator);
        nav.addListernOnRightComponent(new View.OnClickListener(){

			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				System.out.println("Click Nav Right....");
				//房屋地址
				mFWDZet = ((EditText)findViewById(R.id.query_fwdz));
				//房主姓名
				mFZXMet = ((EditText)findViewById(R.id.query_fzxm));
				//房主证件号码
				mFZZJHMZet = ((EditText)findViewById(R.id.query_fzzjhm));
				//承租人姓名
				mCZRXMet = ((EditText)findViewById(R.id.query_czrxm));
				//承租人证件号码
				mCZRZJHMet = ((EditText)findViewById(R.id.query_czrzjhm));
				//登记日期
//				mDateDisplay = 
				mPb = (ProcessingBar) findViewById(R.id.query_pro_bar);
				mQueryForm = findViewById(R.id.query_form);
				
				//构造查询条件，并把参数放入Map中
				HashMap<String,String> paraMap = new HashMap<String,String>();
				paraMap.put(HouseConstants.KEY_FWDZ, mFWDZet.getText().toString());
				paraMap.put(HouseConstants.KEY_FZXM, mFZXMet.getText().toString());
				paraMap.put(HouseConstants.KEY_FZZJHM, mFZZJHMZet.getText().toString());
				paraMap.put(HouseConstants.KEY_CZRXM, mCZRXMet.getText().toString());
				paraMap.put(HouseConstants.KEY_CZRZJHM, mCZRZJHMet.getText().toString());
				paraMap.put(HouseConstants.KEY_DJRQ, mDateDisplay.getText().toString());
				paraMap.put(HouseConstants.KEY_QUERY_FROM, "0");//第一次查询 From为0
				paraMap.put(HouseConstants.KEY_CNT_PER_QUERY, HouseConstants.DEFAULT_CNT_PER_QUERY);//设置默认结果集大小10
				
				QueryGeneralInfoTask doquery = new QueryGeneralInfoTask();
				doquery.execute(paraMap);
			}
        	
        });
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
    }
    
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
            		.append(mYear).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mDay));                    
    }
    
    private class QueryGeneralInfoTask extends AsyncTask<HashMap<String,String>, Void, HashMap<String,?>>{

		@SuppressWarnings({ "unchecked", "rawtypes"})
		@Override
		protected HashMap<String,?> doInBackground(HashMap<String,String>... params) {	
			System.out.println("doInBackground");
			HashMap result = new HashMap();
			result.put(HouseConstants.KEY_SEARCH_CONDITION, params[0]);	
			HouseInforDataAccessor dataAccessor = HouseInforDataAccessorFactory.getHouseDataAccessor(0);
			result.put(HouseConstants.KEY_RESULT,dataAccessor.queryGeneralHouseInformation(params[0]));
//			System.out.println(result);
			return result;			
		}

		@SuppressWarnings("rawtypes")
		@Override
		protected void onPostExecute(HashMap<String,?> result) {
			super.onPostExecute(result);
			System.out.println("onPostExecute" + result);
			if(result.containsKey(HouseConstants.KEY_RESULT)){
				final HashMap reMap = (HashMap)result.get(HouseConstants.KEY_RESULT);
				if(reMap.containsKey(HouseConstants.KEY_RESULT_ERROR)){//查询失败，返回原页面并提示。
					mQueryForm.setVisibility(View.VISIBLE);
					mPb.setVisibility(View.GONE);
					Toast.makeText(QueryConditionActivity.this,reMap.get(HouseConstants.KEY_RESULT_ERROR).toString(), Toast.LENGTH_SHORT).show();
				}else if(((HashMap)result.get(HouseConstants.KEY_RESULT)).containsKey(HouseConstants.KEY_RESULT_SUCCESS)){//查询成功，跳转页面
					Intent intent = new Intent(QueryConditionActivity.this,ListGeneralResultActivity.class);
					intent.putExtra(HouseConstants.KEY_RESULT, (Serializable)((HashMap)result.get(HouseConstants.KEY_RESULT)).get(HouseConstants.KEY_RESULT_SUCCESS));
					System.out.println((Serializable)((HashMap)result.get(HouseConstants.KEY_RESULT)).get(HouseConstants.KEY_RESULT_SUCCESS));
					intent.putExtra(HouseConstants.KEY_SEARCH_CONDITION, (Serializable)result.get(HouseConstants.KEY_SEARCH_CONDITION));
					System.out.println((Serializable)result.get(HouseConstants.KEY_SEARCH_CONDITION));
					QueryConditionActivity.this.startActivity(intent);  
//					QueryConditionActivity.this.finish();
				}
			}else{
				mQueryForm.setVisibility(View.VISIBLE);
				mPb.setVisibility(View.GONE);
				Toast.makeText(QueryConditionActivity.this,"无法解析服务器返回数据!", Toast.LENGTH_SHORT).show();
			}						
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();			
			System.out.println("On pre execute...");
			//隐藏软键盘
			InputMethodManager imm = (InputMethodManager)QueryConditionActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(mQueryForm.getWindowToken(), 0);
			mQueryForm.setVisibility(View.GONE);
			mPb.setVisibility(View.VISIBLE);
		}   	
    }
}
